import { GetToken } from "@/utils/auth";

const MAX_RETRIES = 2;
const RETRY_DELAY = 1000;
const BASE_URL = 'http://localhost:8090';

// 修复后的发送聊天消息函数 - 正确解析SSE格式
export async function getExchange(data, chatId, onRealTimeUpdate, retryCount = 0) {
    try {
        const url = new URL(`${BASE_URL}/ai/chat`);

        // 正确处理请求数据
        let requestBody;
        let contentType = {};

        if (data instanceof FormData) {
            requestBody = data;
            // 浏览器会自动设置multipart/form-data
        } else {
            requestBody = new URLSearchParams({ prompt: data });
            contentType = { 'Content-Type': 'application/x-www-form-urlencoded' };
        }

        if (chatId) {
            url.searchParams.append('chatId', chatId);
        }

        const token = GetToken();
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Accept': 'text/event-stream',
                ...contentType,
                ...(token ? { 'token': token } : {})
            },
            body: requestBody
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let buffer = '';
        let accumulatedContent = '';

        while (true) {
            const { done, value } = await reader.read();

            if (done) {
                console.log('Stream finished');
                break;
            }

            // 解码数据
            buffer += decoder.decode(value, { stream: true });

            // 按行分割处理SSE格式
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留不完整的行

            for (let line of lines) {
                line = line.trim();

                if (line.startsWith('data:')) {
                    const dataContent = line.substring(5).trim();

                    // 跳过结束标记和空数据
                    if (dataContent === '[DONE]' || !dataContent) {
                        continue;
                    }

                    // 累积有效内容
                    accumulatedContent += dataContent;

                    // 实时回调更新（传递累积的内容）
                    if (onRealTimeUpdate && typeof onRealTimeUpdate === 'function') {
                        onRealTimeUpdate(dataContent, accumulatedContent);
                    }
                }
            }
        }

        // 最终清理内容
        const finalContent = cleanContent(accumulatedContent);
        return finalContent || '对话完成';

    } catch (error) {
        console.error('API Error:', error);

        if (retryCount < MAX_RETRIES) {
            console.log(`第${retryCount + 1}次重试...`);
            await new Promise(resolve => setTimeout(resolve, RETRY_DELAY * Math.pow(2, retryCount)));
            return getExchange(data, chatId, onRealTimeUpdate, retryCount + 1);
        }

        console.error('所有重试都失败');
        throw error;
    }
}

// 内容清理函数
function cleanContent(content) {
    return content
        .replace(/<think>.*?<\/think>/gs, '')  // 移除think标签
        .replace(/DeepSeek-R1-Lite-Preview/g, '王饲预')  // 替换名称
        .replace(/\s+/g, ' ')  // 合并多余空格
        .trim();
}